package com.dj.msgtable.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dj.msgtable.commom.ExcelRead;
import com.dj.msgtable.commom.ExcelUtil;
import com.dj.msgtable.commom.PhoneNumber;
import com.dj.msgtable.commom.TimeGet;
import com.dj.msgtable.entity.Custom;
import com.dj.msgtable.entity.User;
import com.dj.msgtable.service.CustomService;
import com.dj.msgtable.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class LoginController {


    @Autowired
    CustomService customService;
    @Autowired
    UserService userService;
    @RequestMapping("/login")
    public void loginPage(HttpServletResponse response, HttpServletRequest request){
        System.out.println( request.getRequestURI());
        try {
            response.sendRedirect("/msgtable/html/login.html");
            System.out.println("------------------------------------------------------------------------");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//    判断是否登录
    @PostMapping( "/login/whetherLogin")
    @ResponseBody
    public String whetherLogin(HttpServletRequest request,HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Object object =  session.getAttribute("user");

        String tmp = "tmp";
        if (object!=null){
            User user = (User) object;
            return user.getRank();
        }
        return null;
    }
//    登录判断
    @PostMapping( "/login/judge")
    @ResponseBody
    public boolean judjeLogin(HttpServletRequest request,HttpServletResponse response,@RequestBody User user) throws IOException {
        HttpSession session = request.getSession();
        User dbUser = userService.searchUser(user);
//        System.out.println(dbUser.toString());
        if (dbUser!=null){
            session.setAttribute("user",dbUser);
            System.out.println(true);
            return true;
        }else{
            System.out.println(false);
            return false;
        }
    }
//    查找用户列表
    @PostMapping( "/login/searchUserlist")
    @ResponseBody
    public List<User> searchUserList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Object object =  session.getAttribute("user");
//        Object object = 1 ;
        if (object!=null){
            User user = (User) object;
            if ("0".equals(user.getRank())){
                System.out.println("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
                return userService.searchUserByHigh(user);
            }else if ("1".equals(user.getRank())){
                System.out.println("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
                return userService.searchUserByMiddle(user);
            }
            return null;
        }
        return null;
    }
    //    查找3级用户列表
    @PostMapping( "/login/searchUser3list")
    @ResponseBody
    public List<User> searchUser3List(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Object object =  session.getAttribute("user");
        if (object!=null){
            User user = (User) object;
            if ("0".equals(user.getRank())){
                return userService.searchUserByMiddle(user);
            }else if ("1".equals(user.getRank())){
                return userService.searchUserByMiddle(user);
            }
            return null;
        }
        return null;
    }

    //    添加用户
    @PostMapping( "/login/Adduser")
    @ResponseBody
    public String addUser(HttpServletRequest request,@RequestBody User user) throws Exception {
        System.out.println("----------------------------------------------------------------");
        HttpSession session = request.getSession();
        Object object =  session.getAttribute("user");
        if (object!=null){
            User sessionuser = (User) object;
            if ("0".equals(sessionuser.getRank())){
                if (searchUserWhetherExist(user)){
                    userService.addUserByHigh(user);
                    return "插入成功";
                }else {
                    return "用户名已存在";
                }
            }else if ("1".equals(sessionuser.getRank())){
                if (searchUserWhetherExist(user)){
                    userService.addUserByMiddle(user);
                    return "插入成功";
                }else {
                    return "用户名已存在";
                }
            }
        }
        return "新增失败";
//        return true;
    }
//    查看用户名是否存在
    public boolean searchUserWhetherExist(User user){
        if (userService.searchUserByName(user)==null){
            return true;
        }
        return false;
    }


    @GetMapping("/login/AddCustom")
    public String upload() {
        return "/login/AddCustom";
    }


//    @PostMapping( "/login/AddCustom")
    @ResponseBody
    public void addCustom(HttpServletRequest request,HttpServletResponse response,@RequestParam("file") MultipartFile file) throws Exception {
        System.out.println("----------------------------------------------------------------");
        HttpSession session = request.getSession();
        Object object = 1 ;
//        Object object = session.getAttribute("user");
//        if (object != null) {
//            User sessionuser = (User) object;
        User sessionuser =new User();
        sessionuser.setRank("1");
            if ("0".equals(sessionuser.getRank())||"1".equals(sessionuser.getRank())) {
//                String originalFilename = file.getOriginalFilename();
//                String type = file.getContentType();
//                //originalFilename = UUID.randomUUID().toString()+originalFilename;
//                System.out.println("目标文件名称：" + originalFilename + ",目标文件类型：" + type);
//                InputStream is = file.getInputStream();
//                ImportExcel importExcel = new ImportExcel();
////                Workbook createWorkbook = importExcel.createWorkbook(is, type);
//                List<Object> list = importExcel.importDataFromExcel(is, originalFilename);
//                for (int i = 0; i < list.size(); i++) {
//                    System.out.println(list.get(i).toString());
//                }

                JSONObject json = new JSONObject();

//                return json;
//            }
        }

        response.sendRedirect("/msgtable/html/formsubmit.html");
    }


//    @PostMapping("/login/AddCustom")
    @ResponseBody
    public String upload(HttpServletRequest request,HttpServletResponse response,@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }


        String fileName = file.getOriginalFilename();
        String filePath = "C:/temp/";
        File dest = new File(filePath + fileName);









        try {
            file.transferTo(dest);
//            LOGGER.info("上传成功");
            return "上传成功";
        } catch (IOException e) {
//            LOGGER.error(e.toString(), e);
        }
        return "上传失败！";
    }



    public boolean jiexi(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        // 判断文件是.xlsx或者xls结尾。如果不是则抛出提示信息
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (!"xlsx".equals(suffix) && !"xls".equals(suffix)) {

            System.out.println("请传入excel文件");
            return false;
        }
        return true;
    }

    /**
     * 读取Excel数据到数据库
     * @param file
     * @param request
     * @return
     * @throws IOException
     * @author lp
     */
    @PostMapping("/login/AddCustom")
//    @RequestMapping("/login/AddCustom")
    @ResponseBody
    public String readExcel(@RequestParam(value="file") MultipartFile file, HttpServletRequest request) throws IOException{
        //判断文件是否为空

        HttpSession session = request.getSession();
        Object object =  session.getAttribute("user");

        if (object!=null) {
            User sessionuser = (User) object;
        if(file == null){
            return null;
        }
        String name = file.getOriginalFilename();
        long size = file.getSize();
        if(name == null || ExcelUtil.EMPTY.equals(name) && size==0){
            return null;
        }
        //读取Excel数据到List中
        List<ArrayList<String>> list = new ExcelRead().readExcel(file);
        //list中存的就是excel中的数据，可以根据excel中每一列的值转换成你所需要的值（从0开始），如：
        Integer inputLength = list.size();//上传数据量
        Integer errphone = 0;             //错误手机号数量
        Integer repeatphone = 0;          //重复手机号数量

            JSONArray jsonArray = new JSONArray();


//        List<Custom> customs = new ArrayList<>();
        for(ArrayList<String> arr:list) {
//            custom.setAuthor(list.get(0));//每一行的第一个单元格
            if (arr.size()>4) {
                Custom custom = new Custom();
                custom.setPhone(arr.get(4));
                System.out.println("==============================================================================" + arr.size());
                if (PhoneNumber.isMobileNO(custom.getPhone())) {
                    if (StringUtils.isEmpty(customService.searchCustombyPhone(custom))) {
                        custom.setRealName(arr.get(0));
                        custom.setPlatform(arr.get(1));
                        custom.setOrigin(arr.get(2));
                        custom.setAccount(arr.get(3));
//                   custom.setPhone(arr.get(4));
                        if (arr.size() > 5) {
                            custom.setQq(arr.get(5));
                        }
                        if (arr.size() > 6) {
                            custom.setRemarks(arr.get(6));
                        }
                        if (arr.size() > 7) {
                            custom.setUrl(arr.get(7));
                        }
                        if (arr.size() > 8) {
                            custom.setKeyword(arr.get(8));
                        }
                        if (arr.size() > 9) {
                            custom.setResourceForm(arr.get(9));
                        }
                        if (arr.size() > 10) {
                            custom.setProject(arr.get(10));
                        }
                        if (arr.size() > 11) {
                            custom.setArea(arr.get(11));
                        }
                        custom.setInputTime(TimeGet.nowTimeSteing());
                        custom.setStatus("新入库");

                        if ("2".equals(sessionuser.getRank())) {
                            custom.setFollowUser(String.valueOf(sessionuser.getId()));
                            customService.addCustomHavef(custom);
                        } else {
                            customService.addCustomNof(custom);
                        }

                    } else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("0", arr.get(0));
                        jsonObject.put("1", arr.get(1));
                        jsonObject.put("2", arr.get(2));
                        jsonObject.put("3", arr.get(3));
                        jsonObject.put("4", arr.get(4));
                        if (arr.size() > 5) {
                            jsonObject.put("5", arr.get(5));
                        }
                        if (arr.size() > 6) {
                            jsonObject.put("6", arr.get(6));
                        }
                        if (arr.size() > 7) {
                            jsonObject.put("7", arr.get(7));
                        }
                        if (arr.size() > 8) {
                            jsonObject.put("8", arr.get(8));
                        }
                        if (arr.size() > 9) {
                            jsonObject.put("9", arr.get(9));
                        }
                        if (arr.size() > 10) {
                            jsonObject.put("10", arr.get(10));
                        }
                        if (arr.size() > 11) {
                            jsonObject.put("11", arr.get(11));
                        }
                        jsonObject.put("12", "重复手机号");
                        jsonArray.add(jsonObject);
                        repeatphone++;

                    }
                } else {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("0", arr.get(0));
                    jsonObject.put("1", arr.get(1));
                    jsonObject.put("2", arr.get(2));
                    jsonObject.put("3", arr.get(3));
                    jsonObject.put("4", arr.get(4));
                    if (arr.size() > 5) {
                        jsonObject.put("5", arr.get(5));
                    }
                    if (arr.size() > 6) {
                        jsonObject.put("6", arr.get(6));
                    }
                    if (arr.size() > 7) {
                        jsonObject.put("7", arr.get(7));
                    }
                    if (arr.size() > 8) {
                        jsonObject.put("8", arr.get(8));
                    }
                    if (arr.size() > 9) {
                        jsonObject.put("9", arr.get(9));
                    }
                    if (arr.size() > 10) {
                        jsonObject.put("10", arr.get(10));
                    }
                    if (arr.size() > 11) {
                        jsonObject.put("11", arr.get(11));
                    }
                    jsonObject.put("12", "错误手机号");
                    jsonArray.add(jsonObject);
                    errphone++;
                }
//            System.out.println(custom.toString());
            }
        }
            Integer successMsg = inputLength - errphone - repeatphone;
            String backMessage = "上传数据" + inputLength + "   上传成功  " + successMsg + "   错误手机号数量  " + errphone + "   重复手机号数量  " + repeatphone;
            JSONObject jb = new JSONObject();
            jb.put("msg", backMessage);
            jb.put("tmp", errphone + repeatphone);
            jb.put("jsonobject", jsonArray);
            System.out.println(jb.toString());
            return jb.toString();

        }
        return null;
    }
//    @PostMapping("/login/AddCustom")
    public void readExcel(HttpServletResponse response) throws IOException {
        response.sendRedirect("/msgtable/html/formsubmit.html");
    }
////判断是否是手机号
//    public boolean isMobileNO(String mobiles) {
//        Pattern p = Pattern.compile("0?(13|14|15|18|17)[0-9]{9}");
//        Matcher m = p.matcher(mobiles);
//        return m.matches();
//    }
//    查找用户列表
    @PostMapping( "/login/searchFollowlist")
    @ResponseBody
    public List<User> searchList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Object object =  session.getAttribute("user");
    //        Object object = 1 ;
        if (object!=null){
            User user = (User) object;
            if ("0".equals(user.getRank())){
                return userService.searchUserByMiddle(user);
            }else if ("1".equals(user.getRank())){
                return userService.searchUserByMiddle(user);
            }
            return null;
        }
        return null;
    }

    @PostMapping( "/login/loginout")
    @ResponseBody
    public String loginOut(HttpServletRequest request,HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        return null;
    }
}
